package ar.edu.itba.it.paw.web.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import ar.edu.itba.it.paw.web.command.RegisterUserForm;

@Component
public class RegisterUserFormValidator implements Validator{

	@Override
	public boolean supports(Class<?> clazz) {
		return RegisterUserForm.class.equals(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		RegisterUserForm form = (RegisterUserForm)target;
		
		if(form.getUsername().equals("")){
			errors.rejectValue("username", "empty");
		}
		if(form.getUsername().length() > 20){
			errors.rejectValue("username", "too_long");
		}
		if(form.getPassword().equals("")){
			errors.rejectValue("password", "empty");
		}else{
			if(form.getPassword().length() < 8){
				errors.rejectValue("password", "too_short");
			}
			if(form.getConf_password().equals("")){
				errors.rejectValue("conf_password", "empty");
			}
		}

		if(!form.getPassword().equals(form.getConf_password())){
			errors.rejectValue("conf_password", "not_matching");
		}
		if(form.getSurname().equals("")){
			errors.rejectValue("surname", "empty");
		}
		if(form.getName().equals("")){
			errors.rejectValue("name", "empty");
		}
		if(form.getMail().equals("")){
			errors.rejectValue("mail", "empty");
		}else{
			if(!form.getMail().contains("@")){
				errors.rejectValue("mail", "invalid");
			}
		}
	}
}
